package com.ruoyi.quartz.task;

import com.ruoyi.slope.data.crack.domain.SlopeCrackData;
import com.ruoyi.slope.data.crack.mapper.SlopeCrackDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2025/9/5 下午9:30
 */
@Component("SlopeChangeRateTask")
public class SlopeChangeRateTask {

    @Autowired
    private SlopeCrackDataMapper slopeCrackDataMapper;

    /**
     * 每10分钟执行一次
     */
    public void calculateChangeRate() {
        // 查询最近一天的所有数据（1440分钟）
        List<SlopeCrackData> list = slopeCrackDataMapper.selectRecentData(1440 * 1); // 1天

        if (list == null || list.isEmpty()) {
            System.out.println("【定时任务】无数据需要处理");
            return;
        }

        // 按设备保存当天第一条有速率的数据
        Map<String, SlopeCrackData> firstWithRate = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 先按时间排序，保证顺序处理
        list.sort(Comparator.comparing(SlopeCrackData::getCreateTime));

        for (SlopeCrackData data : list) {
            if (data.getCrackOrAngle() == null || data.getCrackOrAngle() != 0) {
                continue; // 只处理 crackChange
            }

            // ✅ 超过 100mm 的数据直接忽略
            if (data.getCrackChange() != null && Math.abs(data.getCrackChange()) > 1) {
                continue;
            }

            String deviceSn = data.getDeviceSn();
            String dayKey = deviceSn;

            SlopeCrackData first = firstWithRate.get(dayKey);

            if (first == null) {
                // 首条数据，如果 changeRate 为空，则初始化为0
                SlopeCrackData temp = new SlopeCrackData();
                temp.setId(data.getId());
                temp.setDeviceSn(deviceSn);
                temp.setCrackChange(data.getCrackChange());
                temp.setChangeRate(data.getChangeRate() != null ? data.getChangeRate() : 0.0);
                firstWithRate.put(dayKey, temp);
            } else {
                // 累加速率计算
                double prevChange = first.getCrackChange();
                double prevRate = first.getChangeRate() != null ? first.getChangeRate() : 0.0;
                double currentChange = data.getCrackChange();

                // 计算累加后的速率
                double newRate = prevChange + prevRate - currentChange ;

                // 更新数据库
                slopeCrackDataMapper.updateCrackChangeRate(data.getId(), newRate);

                // 更新 firstWithRate 用于下一条累加
                first.setCrackChange(currentChange);
                first.setChangeRate(newRate);
            }
        }

        System.out.println("【定时任务】crack_change_rate 计算完成，共处理：" + list.size() + " 条数据");
    }

    public void calculateTiltRate() {
        // 查询最近一天的所有倾斜角数据（1440分钟）
        List<SlopeCrackData> list = slopeCrackDataMapper.selectRecentAngleData(1440);

        if (list == null || list.isEmpty()) {
            System.out.println("【定时任务】无数据需要处理");
            return;
        }

        // 按设备保存当天第一条有速率的数据
        Map<String, SlopeCrackData> firstWithRate = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 按时间升序排序
        list.sort(Comparator.comparing(SlopeCrackData::getCreateTime));

        for (SlopeCrackData data : list) {
            if (data.getCrackOrAngle() == null || data.getCrackOrAngle() != 1) {
                continue;
            }

            String deviceSn = data.getDeviceSn();
            String dayKey = deviceSn;
            SlopeCrackData first = firstWithRate.get(dayKey);

            if (first == null) {
                // 首条数据初始化
                SlopeCrackData temp = new SlopeCrackData();
                temp.setId(data.getId());
                temp.setDeviceSn(deviceSn);
                temp.setXTiltAngle(data.getXTiltAngle() != null ? data.getXTiltAngle() : 0.0);
                temp.setYTiltAngle(data.getYTiltAngle() != null ? data.getYTiltAngle() : 0.0);
                temp.setZTiltAngle(data.getZTiltAngle() != null ? data.getZTiltAngle() : 0.0);
                temp.setXyTiltAngle(data.getXyTiltAngle() != null ? data.getXyTiltAngle() : 0.0);

                // 初始化 change rate
                temp.setXTiltAngleChangeRate(0.0);
                temp.setYTiltAngleChangeRate(0.0);
                temp.setZTiltAngleChangeRate(0.0);
                temp.setXyTiltAngleChangeRate(0.0);

                firstWithRate.put(dayKey, temp);
            } else {
                // 累加速率计算
                double currentX = data.getXTiltAngle() != null ? data.getXTiltAngle() : 0.0;
                double currentY = data.getYTiltAngle() != null ? data.getYTiltAngle() : 0.0;
                double currentZ = data.getZTiltAngle() != null ? data.getZTiltAngle() : 0.0;
                double currentXY = data.getXyTiltAngle() != null ? data.getXyTiltAngle() : 0.0;

                double newXRate = first.getXTiltAngle() + first.getXTiltAngleChangeRate() - currentX;
                double newYRate = first.getYTiltAngle() + first.getYTiltAngleChangeRate() - currentY;
                double newZRate = first.getZTiltAngle() + first.getZTiltAngleChangeRate() - currentZ;
                double newXYRate = first.getXyTiltAngle() + first.getXyTiltAngleChangeRate() - currentXY;

                // 更新数据库
                slopeCrackDataMapper.updateTiltAnglesChangeRate(
                        data.getId(),
                        newXRate,
                        newYRate,
                        newZRate,
                        newXYRate
                );

                // 更新 first 用于下一条累加
                first.setXTiltAngle(currentX);
                first.setYTiltAngle(currentY);
                first.setZTiltAngle(currentZ);
                first.setXyTiltAngle(currentXY);

                first.setXTiltAngleChangeRate(newXRate);
                first.setYTiltAngleChangeRate(newYRate);
                first.setZTiltAngleChangeRate(newZRate);
                first.setXyTiltAngleChangeRate(newXYRate);
            }
        }

        System.out.println("【定时任务】倾斜角累加速率计算完成，共处理：" + list.size() + " 条数据");
    }
}
